load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_code.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_csm.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/wrf/WRFUserARW.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/wrf/WRF_contributed.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/contrib/ut_string.ncl"
load "/public/users/wrf/Codes/WRF_scripts/utils/substring.ncl"
load "/public/users/wrf/Codes/WRF_scripts/utils/WRF_dyy_contributed.ncl"


;===============================================================================
; Begin of Main Process
;===============================================================================

if (.not. isvar("fb_hour")) then
    fb_hour = 8
end if

if (.not. isvar("stn_name")) then
    stn_name = "pukou"
    stn_num  = "27001"
end if

fb_hour_str = sprinti("%02i", fb_hour)

;;; read NWP predicted wind data ;;;
; get nwp output txt file list, prediction time start at 20:00
nwpTxtPath        = "/public/users/wrf/wrfpost/txt/station_allvalue/pukou/d02/08/"

delayTime = 8 + fb_hour

if (fb_hour .eq. 8) then
    nwpTxtFileList = systemfunc("find " + nwpTxtPath + " -name allvalue_*" + stn_name +"_d02_2012-*_00.csv |sort")
else
    nwpTxtFileList = systemfunc("find " + nwpTxtPath + " -name allvalue_*" + stn_name + "_d02_2012-*_12.csv |sort")
end if
nFile             = dimsizes(nwpTxtFileList)

dt           = 0.25 ; time resolution: 30min
allRecSize   = tointeger(nFile*24/dt)
allRecStrs   = new(allRecSize, "string")
nRecDaily    = tointeger(24/dt)

; read wind data from each file
do ifile = 0, dimsizes(nwpTxtFileList) - 1
    print("processing " + nwpTxtFileList(ifile))
    lines = ndtooned(readAsciiTable(nwpTxtFileList(ifile),1,"string",1))

    timeStr_t   = ndtooned(str_get_field(lines, 3, ","))
    time_udunit_t = timestr_to_udunits(timeStr_t)

    ; find the period of 24h prediction
    predictionStartTime = time_udunit_t(0)
    firstValidTime      = predictionStartTime + delayTime
    lastValidTime       = predictionStartTime + delayTime + 24
    copy_VarAtts(predictionStartTime, firstValidTime)
    copy_VarAtts(predictionStartTime, lastValidTime)
    index_first = ind_nearest_coord(firstValidTime, time_udunit_t, 0)
    index_last  = ind_nearest_coord(lastValidTime, time_udunit_t, 0) - 1

    print(predictionStartTime + "," + timeStr_t(0))
    print(index_first + ", " + firstValidTime +", " + time_udunit_t(index_first) + "," + timeStr_t(index_first))
    print(index_last + ", " + lastValidTime +", " + time_udunit_t(index_last) +  "," + timeStr_t(index_last))
    allRecStrs(ifile*nRecDaily:((ifile+1)*nRecDaily-1)) = lines(index_first:index_last)

    delete(lines)
    delete(timeStr_t)
    delete(time_udunit_t)
end do

;print(allRecStrs)

; write to csv file
output_meas_csvfile = "~/wrfpost/test/" + stn_name + "_" + stn_num + "_predict_08_2012_11.csv"
asciiwrite(output_meas_csvfile, allRecStrs)
